<script setup>
import { onMounted, ref } from 'vue'
import { getAllApi, getByIdApi, updateByIdApi } from '@/api/outbound/outboundorderdetails'
import { savePackageApi } from '@/api/outbound/outboundorderpackage'
import { ElMessage, ElDialog, ElButton } from 'element-plus'
import Display from '@/views/outbound/pendingpick/display.vue'

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const form = ref({
  invoiceCode: '',
  customerId: '',
  skuId: ''
})

// 模拟客户列表
const mockCustomerList = [
  { id: 1001, name: '客户A' },
  { id: 1002, name: '客户B' },
  { id: 1003, name: '客户C' },
  { id: 1004, name: '客户D' }
]

const getCustomerName = (customerId) => {
  const customer = mockCustomerList.find(item => item.id === customerId)
  return customer ? customer.name : '未知客户'
}

// 获取主表数据
const getAll = async () => {
  const res = await getAllApi(
    form.value.invoiceCode,
    form.value.customerId,
    form.value.skuId,
    currentPage.value,
    pageSize.value
  )
  total.value = res.total
  tableData.value = res.rows
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getAll()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getAll()
}

const search = () => {
  currentPage.value = 1
  getAll()
}

// 打开详情弹窗
const visible = ref(false)
const selectedRow = ref(null)
const detailList = ref([])

const handleEdit = async (row) => {
  selectedRow.value = row
  try {
    const res = await getByIdApi(row.id)
    // 确保返回的是数组
    if (Array.isArray(res.data)) {
      detailList.value = res.data
    } else {
      // 如果是单个对象，转换为数组
      detailList.value = [res.data]
    }
  } catch (error) {
    ElMessage.error('获取明细失败')
  }
  visible.value = true
}

// 拣货确认弹窗
const pickConfirmVisible = ref(false)
const currentPickItem = ref(null)

const handlePick = (item) => {
  currentPickItem.value = item
  pickConfirmVisible.value = true
}

const confirmPick = async () => {
  if (!currentPickItem.value) return

  const { id, skuId, outCount, invoiceCode } = selectedRow.value
  const quantity = currentPickItem.value.quantity || outCount

  try {
    // 1. 更新拣货状态
    const updateRes = await updateByIdApi(id)

    if (updateRes.code !== 1) {
      ElMessage.error(updateRes.msg || '拣货失败')
      return
    }

    // 2. 插入打包表
    const packageData = {
      outbound_order_detail_id: id,
      outbound_order_id: invoiceCode,
      sku_id: skuId,
      package_count: quantity,
      package_emp_id: '',
      package_time: new Date().toISOString(),
      saas_id: window.saasId || '',
      create_by: '',
      create_time: new Date().toISOString()
    }

    const packRes = await savePackageApi(packageData)
    if (packRes.code !== 1) {
      ElMessage.warning('拣货成功，但打包失败')
    } else {
      ElMessage.success('拣货并打包成功')
    }

    getAll()
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  } finally {
    pickConfirmVisible.value = false
    visible.value = false
  }
}

onMounted(() => {
  getAll()
})
</script>

<template>
  <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
  </div>

  <el-form :model="form" :inline="true" style="margin-bottom: 20px;">
    <el-form-item label="发货单号">
      <el-input v-model="form.invoiceCode" placeholder="请输入发货单号" />
    </el-form-item>
    <el-form-item label="客户名称">
      <el-input v-model="form.customerId" placeholder="请输入客户姓名" />
    </el-form-item>
    <el-form-item label="商品名称">
      <el-input v-model="form.skuId" placeholder="请输入商品ID" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="invoiceCode" label="发货单号" />
    <el-table-column prop="customerId" label="客户姓名">
      <template #default="{ row }">
        {{ getCustomerName(row.customerId) }}
      </template>
    </el-table-column>
    <el-table-column prop="code" label="商品编码" />
    <el-table-column prop="title" label="商品名称" />
    <el-table-column prop="description" label="商品描述" />
    <el-table-column prop="barcode" label="条码" />
    <el-table-column prop="outCount" label="订单数量" />
    <el-table-column prop="pendingPickQuantity" label="待拣货数量" />
    <el-table-column prop="pickedQuantity" label="已拣货数量" />
    <el-table-column fixed="right" label="操作" width="200">
      <template #default="{ row }">
        <el-button size="small" @click="handleEdit(row)">查看</el-button>
        <el-button size="small" type="danger" @click="delById(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>

  <!-- 查看详情 Dialog -->
  <el-dialog v-model="visible" title="商品详情" width="80%" :before-close="() => { visible = false }">
    <Display :row="selectedRow" :detail-list="detailList" @pick="handlePick" />
  </el-dialog>

  <!-- 拣货确认 Dialog -->
  <el-dialog v-model="pickConfirmVisible" title="提示" width="400px">
    <div>拣货？</div>
    <template #footer>
      <el-button @click="pickConfirmVisible = false">关闭</el-button>
      <el-button type="primary" @click="confirmPick">确认</el-button>
    </template>
  </el-dialog>
</template>